<?php
namespace app\api\controller;
use app\common\logic\Logic;
use app\common\logic\UserAccount;
use app\common\model\ChatUsers;
use app\common\model\GiftRecord;
use app\common\model\Job;
use app\common\logic\Opinion;
use app\common\model\MyCar;
use app\common\model\Order;
use app\common\model\RechargeConfig;
use app\common\model\Room;
use app\common\model\SkillApply;
use app\common\model\UserGuard;
use app\common\model\UserImg;
use think\Db;
use app\common\model\Users;
use think\Exception;
use think\helper\Time;
use think\Request;
use think\Validate;
use wheat\Wheat;


class User extends Base
{
    //用户id
    protected $user_id = 0;

    public function _initialize()
    {
        parent::_initialize();
        $url = request()->controller();
        $url .= '/'.request()->action();
        $notIntercept = ['Pays/notify','Pays/wechat'];


        if (!in_array($url,$notIntercept)){
            //支付回调不进行拦截
            $this->user_id = $this->checkToken();

        }

        // 为解决融云离线后退出房间用户再次打开app不能在房间在线用户列表出现
        $userInfo = $this->userExtra('room_id,online_status');

        //调用接口时如果用户不在线  修改为在线状态
        if ($userInfo['online_status'] == 0){
            $update['online_status'] = 1;
        }

        if (!empty($update)){
            self::updateUserExtend($this->user_id,$update);
        }



    }


    /**
     * 退出登陆
     */
    public function loginOut()
    {
        cache('token_'.hashid($this->user_id),null);
        api_return(1,'退出成功');
    }




    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户会员信息
     */
    protected function userNoble($field = '',$user_id = null,$cache = 15){
        if ($user_id){
            $map['user_id'] = $user_id;
        }else{
            $map['user_id'] = $this->user_id;
        }
        $noble_id =  Db::name('user_extend')->where($map)->value('noble_id');
        $data = Db::name('noble')->where('noble_id',$noble_id)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr = explode(',',$field);
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
        }else{
            return $data[$field];
        }
    }



    /**
     * 获取用户信息
     */
    public function getUser()
    {
        $where['a.user_id'] = $this->user_id;

        $model  = new Users();
        $result = $model->getDetail($where);
        $result['noble_id'] = self::checkNoble($result);
        $result['package'] = 1;
        $result['images'] = UserImg::getList(['user_id'=> $this->user_id]);
        $result['cars'] = (new MyCar())->getMyCar(['m.user_id'=> $this->user_id,'m.status'=>1]);
        $result['skills'] = SkillApply::getMyList(['a.user_id' => $this->user_id,'a.status' => 1]);
        $result['gifts'] = SkillApply::getGifts(['user_id' => $this->user_id,'status' => 1]);

        api_return(1, '获取成功', $result);
    }

    /**
     * 查询个人资料
     */
    public function info()
    {
        $model = new Users();
        $data  = $model->getInfo($this->user_id);
        api_return(1,'获取成功',$data);
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 形象照修改||添加
     */
    public function editImg()
    {
        $data = request()->only(['img_id','img'],'post');

        if (!$data['img']) api_return(0,'请上传图片');

        $data['update_time'] = time();

        $map['user_id'] = $this->user_id;
        $map['status']  = 1;

        if (is_numeric($data['img_id'])){  //形象照修改

            $map['img_id']  = $data['img_id'];
            $img_id = Db::name('user_img')->where($map)->value('img_id');
            if ($img_id){

                $result = Db::name('user_img')->update($data);
                if ($result){
                    api_return(1,'修改成功',['img_id'=>$data['img_id'],'img'=>$data['img']]);
                }else{
                    api_return(0,'修改失败');
                }
            }
            api_return(0,'非法参数');
        }

        //形象照添加

        $num = Db::name('user_img')->where($map)->count();
        $max = Db::name('extend')->where('id',1)->cache(60)->value('img_max');

        if ($num >= $max){
            api_return(0,'形象照最多只允许上传'.$max.'张');
        }

        $data['create_time'] = time();
        $data['user_id']     = $this->user_id;
        $result = Db::name('user_img')->strict(false)->insert($data);
        if ($result){
            api_return(1,'上传成功',['img_id'=>Db::name('user_img')->getLastInsID(),'img'=>$data['img']]);
        }else{
            api_return(0,'上传失败');
        }

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 形象照删除
     */
    public function delImg()
    {
        $map = request()->only(['img_id'],'post');
        $map['user_id'] = $this->user_id;
        $map['type'] = 1;
        $map['status'] = 1;
        $img_id = Db::name('user_img')->where($map)->value('img_id');
        if (!$img_id) api_return(0,'参数错误');
        $result = Db::name('user_img')->delete($img_id);
        if ($result) api_return(1,'删除成功');
        api_return(0,'删除失败');
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 个人资料编辑
     */
    public function editInfo(Request $request)
    {

        $data = $request->only(['header_img','nick_name','sex','sign','birthday','images','bg']);
        if (empty($data)){
            api_return(0,'请输入要修改的参数');
        }
        $validate = new Validate([
            'nick_name' => 'max:20',
            'sex' => 'in:1,2',
        ]);
        if (!$validate->check($data)) {
            get_error_msg($validate->getError());
        }

        $user = \app\common\logic\Users::get($this->user_id);

        $item['after']   = '';
        $item['user_id'] = $this->user_id;
        $item['create_time'] = time();
        $item['update_time'] = time();
        $item['type'] = 2;

        $str = '修改成功';

        if ($data['header_img']){

            $item['before'] = $user['header_img'];
            if ($item['before'] != $data['header_img']){
                $item['after']  = $data['header_img'];
                $item['type']   = 1;
                $item['remark'] = '修改头像';
                Db::name('check')->insert($item);
                unset($data['header_img']);
                $str = '头像修改需系统审核后才能显示,请耐心等待';
            }

        }

        //形象照添加
        if(!empty($data['images']))
        {

            if ($data['images'] !== $this->userExtra('imgs')){
                if (substr_count($data['images'],',') >= 9){
                    api_return(0,'形象照最多只允许上传9张');
                }

                $map['img_id']  = $data['img_id'];
                $img = Db::name('user_extend')->where('user_id',$this->user_id)->value('imgs');
                $item['after']   = $data['images'];
                $item['before']  = $img;
                $item['remark']  = '形象照修改';
                $item['extend']  = $data['img_id'];
                Db::name('check')->insert($item);
                $str = '形象照修改需系统审核后才能显示,请耐心等待';
//                Db::name('user_extend')->where('user_id',$this->user_id)->update(['imgs'=> $data['images']]);

                //            if (count($data['images']) > 9){
//                api_return(0,'形象照最多只允许上传9张');
//            }
//            $images=[];
//            foreach ($data['images'] as $image)
//            {
//                $images[]['img'] = $image;
//            }
//            $user->images()->delete();
//            $user->images()->saveAll($images);

            }

        }

        if (isset($data['nick_name']) && empty($data['nick_name'])){
            unset($data['nick_name']);
        }

        unset($data['images']);
        $result = $user->update($data,['user_id'=> $this->user_id]);

        if ($result){
            api_return(1,$str);
        }
        api_return(0,$result->getError());
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 用户个人详情
     */
    protected function userDetail($user_id,$this_user = 0)
    {
        $model = new Users();
        $userInfo = $model->getInfo($user_id);

        if (!$userInfo){
            api_return(0,'用户不存在或被禁用!');
        }

        $extra = $this->userExtra('room_id,user_id,place,online_status,online_time,grade,imgs,job,hobby,fans_num,noble_id,noble_time,level',$user_id);
        $extra['headWear'] = self::getHeadWear($user_id);
        $data  = array_merge($userInfo->getData(),$extra);

        if ($data['imgs']){
            $data['imgs'] = explode(',',$data['imgs']);
        }else{
            $data['imgs'] = [];
        }

        if ($data['room_id']){
            $data['roomInfo'] = $this->roomInfo($data['room_id'],'is_lock,password,room_name');
            if ($this_user){
                $data['roomInfo']['power'] = getPowerCode($this_user,$data['room_id']);
            }else{
                $data['roomInfo']['power'] = 4;
            }
        }else{
            $data['roomInfo']['is_lock'] = 0;
            $data['roomInfo']['password'] = '';
            $data['roomInfo']['room_name'] = '';
            $data['roomInfo']['power'] = 4;
        }


        $data['bg'] = empty($data['bg'])?$this->extend('default_bg'):$data['bg'];

        $where['user_id']    = $user_id;
        $where['type']       = 2;
        $where['status']     = 1;
        $where['money_type'] = 1;
        $data['expend'] = Db::name('money_detail')->where($where)->sum('money');

        $data['user_id'] = hashid($data['user_id']);

        $data['noble_id'] = self::checkNoble($data);

        $data['age'] = getAge($data['birthday']).'岁';
       if ($data['online_status']){
           $data['status'] = '当前在线';
       }else{
           $data['status'] = formatTime($data['online_time']);
       }

        $map['status']  = 1;
        $map['user_id'] = $user_id;

//        $data['vod']     = Db::name('vod')->where($map)->field('pid,play_url,play_num,img')->select();
//
//        $data['vod_max'] = $this->extend('vod_max');

        $gift['a.status']  = 1;
        $gift['a.to_user'] = $user_id;
        $data['gift_count'] = Db::name('gift_record')->alias('a')->where($gift)->sum('a.num');

        $data['gift_list']  = (new GiftRecord())->giftCount($gift);


        $car['a.user_id']  = $user_id;
        $car['a.end_time'] = [['=',0],['>=',\time()],'or'];
        $car['a.type']     = 1;
        $cars = Db::name('my_car')
            ->alias('a')
            ->join('car c','c.car_id = a.car_id')
            ->field('a.end_time,c.thumbnail,c.img,c.car_name')
            ->where($car)
            ->select();

        foreach ($cars as $k => $item){

            if ($item['end_time'] == 0){
                $cars[$k]['end_time'] = '永久';
            }else{
                $cars[$k]['end_time'] = formatTime($item['create_time'],false);
            }

        }

        $data['cars'] = $cars;


//        $group['c.type']    = 2;
//        $group['c.status']  = 1;
//        $group['a.user_id'] = $user_id;
//        $group['a.status']  = 1;
//        $data['group_list'] = (new ChatUsers())->items($group);

        $room['a.status'] = 1;
        $room['a.user_id'] = $user_id;

        //TODO 为房间管理员的房间未加入
//        $data['room_list'] = (new Room())->room($room);

        $data['skill_list'] = self::getSkillList($user_id);

        return $data;

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取用户可用技能列表
     * @param $user_id
     * @return false|\PDOStatement|string|\think\Collection
     *
     */
    protected static function getSkillList($user_id)
    {
        $map['a.user_id'] = $user_id;
        $map['a.status']  = 1;
        $map['a.is_use']  = 1;

        return (new SkillApply())->getMy($map);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 聊天界面获取信息
     */
    public function chatInfo()
    {
        $id = dehashid(input('id'));
        if (!is_numeric($id)) api_return(0,'参数错误');
        $rows['skill_list'] = self::getSkillList($id);
        $rows['is_follow']  = self::isFollow($this->user_id,$id);
        api_return(1,'获取成功',$rows);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 用户自身详情
     */
    public function selfInfo()
    {

        $data = $this->userDetail($this->user_id,$this->user_id);

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.comZ
     * 其它用户详情
     */
    public function otherInfo()
    {

        $user_id = dehashid(input('post.id'));

        if (!is_numeric($user_id)){
            api_return(0,'参数错误');
        }elseif ($user_id == $this->user_id){
//            api_return(0,'应查询个人详情');
        }

        $data = $this->userDetail($user_id,$this->user_id);

        $guard['a.guard_user'] = $user_id;
        $guard['a.status']     = 1;
        $guard['a.end_time']   = ['>',time()];

//        $data['guard'] = UserGuard::Best($guard);

//        $tag['a.user_id'] = $user_id;
//        $tag['a.status']  = ['between','4,5'];

//        $data['InterestTag'] = Order::InterestTag($tag);

        $data['is_follow'] = self::followStatus($this->user_id,$user_id);
        $data['is_friend'] = self::isFriend($this->user_id,$user_id);
        api_return(1,'获取成功',$data);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param int $user_id
     * @param int $follow_user
     * @return int
     * 获取是否关注用户
     */
    protected static function isFollow( $user_id, $follow_user):int
    {

        if (self::followStatus($user_id, $follow_user) == 1){
            return 1;
        }
        return 0;

//        $map['user_id']     = $user_id;
//        $map['follow_user'] = $follow_user;
//        $map['status']      = 1;
//        return Db::name('user_follow')->where($map)->value('status')??0;
    }




    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取职业列表
     */
    public function job()
    {
        $model = new Job();
        $rows  = $model->getList();
        api_return(1,'获取成功',$rows);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取用户标签
     */
    public function getTag()
    {
        $map['a.user_id'] = $this->user_id;
        $map['a.status']  = ['between','4,5'];
        $rows = Order::InterestTag($map,true);
        $rows[] = ['tag'=>'处对象'];
        $rows[] = ['tag'=>'处连麦'];
        api_return(1,'获取成功',$rows);
    }



    /**
     * 修改手机号码
     */
    public function changePhone()
    {
        $data = input('post.');
        $userPhone = Db::name('users')->where('user_id',$this->user_id)->value('phone');
        $this->checkCode($userPhone,'原手机号码验证码错误');
        $this->checkCode('newPhone','新手机号码验证码错误','newCode');
        $has = Db::name('users')->where('phone',$data['newPhone'])->value('user_id');
        if ($has) api_return(0,'新手机号码已注册');
        $result = Db::name('users')->where('user_id',$this->user_id)->update(['phone'=>$data['newPhone']]);
        if ($result !== false) {
            api_return(1,'更换手机成功');
        }
        api_return(0,'更换手机失败');
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 用户钱包余额
     */
    public function wallet()
    {
        $data = $this->userBalance();

        $map['user_id'] = $this->user_id;
        $map['status']  = 1;

        $data['ID'] = Db::name('user_id')->where($map)->value('ID');

        $data['account_id'] = Db::name('user_account')->where($map)->value('account_id');

        api_return(1,'获取成功',$data);
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 用户账户余额
     */
    protected function userBalance($user_id = null)
    {

        if (!$user_id){
            $user_id = $this->user_id;
        }
        $data = Db::name('users')->where('user_id',$user_id)->field('money,cash,coin,gift_coin')->find();
        $data['total'] = bcadd($data['money'],$data['cash'],2);
        return $data;

    }

    /**
     * 用户签到
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function signIn()
    {
        $days = self::userSignIn($this->user_id);
        if (isInt($days)){

            if ($days < 7){
                $coin = 150;
            }elseif ($days >= 30){
                $coin = 520;
            }else{
                $coin = 300;
            }
            Db::name('users')->where('user_id',$this->user_id)->setInc('coin',$coin);
            api_return(1,sprintf('连续签到%s天,获得赠送金币%s',$days,$coin));
        }
        api_return(0,'今日已签到!');

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 扣除用户账户余额
     */
    protected function moneyDec($money = 0,$user_id = null){
        if (!$user_id){
            $user_id = $this->user_id;
        }
        $balance = $this->userBalance($user_id);
        if ($money > $balance['money']) api_return(0,'余额不足');


//        if ($balance['money'] >= $money){
            $result = Db::name('users')->where('user_id',$user_id)->setDec('money',$money);
            if (!$result) api_return(0,'扣款失败');
//        }else{
//            if ($balance['money'] > 0){
//                $next = bcsub($money,$balance['money'],2);
//                $result = Db::name('users')->where('user_id',$user_id)->setDec('money',$balance['money']);
//                if (!$result) api_return(0,'扣款失败');
//            }else{
//                $next = $money;
//            }
//            $result = Db::name('users')->where('user_id',$user_id)->setDec('cash',$next);
//            if (!$result){
//                Db::name('users')->where('user_id',$user_id)->setInc('money',$balance['money']);
//                api_return(0,'扣款失败');
//            }
//        }
    }



    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户账户余额
     */
    public function balance()
    {
        api_return(1,'获取成功',$this->userBalance());
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 充值参数获取
     */
    public function rechargeConfig()
    {
        $data['balance'] = $this->userBalance();

        $map['status'] = 1;

        $model = new RechargeConfig();

        $data['rows']  = $model->getRows($map);

        //查询是否有充值加成卡
        $map1['user_id'] = $this->user_id;
        $map1['type']    = 2;
        $map1['key']     = 3;

        $data['cardNum'] = Db::name('my_package')->where($map1)->value('num')??0;

        api_return(1,'获取成功',$data);
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取我的提现账户
     */
    public function account()
    {

        $type = input('post.type');

        if ($type != 1 && $type != 2) api_return(0,'查询类型错误');

        $map['user_id'] = $this->user_id;
        $map['type']    = $type;

        $data = Db::name('user_account')->field('account_id,real_name,account,remark,status')->where($map)->find();

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 提现账号编辑
     */
    public function editAccount()
    {

        $data = request()->only(['remark','id','account','real_name','type'],'POST');

        if ($data['type'] != 1 && $data['type'] != 2) api_return(0,'账号类型错误');

        $map['user_id'] = $this->user_id;
        $map['type']    = $data['type'];

        $account = Db::name('user_account')->where($map)->find();

        if (is_numeric($data['id'])){

            if ($data['id'] != $account['account_id']) api_return(0,'参数错误');

            if ($account['status'] == 2) api_return(0,'账号正在审核中,请勿重复操作');

        }else{

            //添加时验证
            if ($account) api_return(0,'您已添加有提现账号,不能继续添加新账号');

        }

        $data['user_id'] = $this->user_id;
        $data['status']  = 2;

        $model = new UserAccount();

        $result = $model->saveChange($data);

        if ($result) api_return(1,'提交成功');
        api_return(0,$model->getError());

    }
    
    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 绑定手机号码
     */
    public function bindPhone()
    {
        $user = Db::name('users')->where('user_id',$this->user_id)->field('phone')->find();
        if ($user['phone']) api_return(0,'您已绑定手机,请进行修改');
        $this->checkCode();
        $phone = input('post.phone');
        $info  = Db::name('users')->where('phone',$phone)->value('user_id');
        if ($info) api_return(0,'该手机号码已绑定其它账号!');
        $result = Db::name('users')->where('user_id',$this->user_id)->update(['phone'=>$phone]);
        if ($result)api_return(1,'绑定成功');
        api_return(0,'绑定失败');
    }



    /**
     *   分享二维码、链接获取
     */
    public function qrcode(){
        $where = db('explain')->where(['id'=>12])->value('content');
        $rule  = db('explain')->where(['id'=>13])->value('content');
        $url   = $where.'login/share?user_id='.hashid($this->user_id);
        if(!empty(cache('code'.$this->user_id))){
            $pic = cache('code'.$this->user_id);
        }else{
            $pic = code($url);
            cache('code'.$this->user_id,$pic,24*60*60);
        }
        $data['qrcode'] = $pic;
        $data['url']    = $url;
        $data['rule']   = $rule;
        $data['backGround'] = Db::name('extend')->where('id',1)->value('backGround');
        api_return(1,'',$data);
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 根据用户当前等级和当前经验获取下一等级信息
     */
    protected function nextLevel($level,$experience)
    {

//        var_dump($level,$experience);exit;
        $rows = Db::name('user_level')->cache(300)->select();

        $array = array_key($rows,'level');

        $key = $level+1;
        $data['level']          = $level;
        $data['color']          = $array[$level]['color']??'';
        $data['nexLevel']       = $array[$key]['level'];
        $data['nexColor']       = $array[$key]['color']??'';
        $data['experience']     = $array[$key]['experience'];
        $data['nextExperience'] = $array[$key]['experience'] - $experience;
        if ($data['nextExperience'] < 0){
            $data['nextExperience'] = 0;
        }
        return $data;
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 根据经验值及当前等级获取应该修改的等级  用于升级时判断
     */
    protected function levelNum($experience = 0,$level = 0)
    {
        $rows = Db::name('user_level')->cache(300)->select();

        $array = array_key($rows,'level');

        $max = count($array);
        for ($i = $level;$i <= $max;$i++){
            $options = ['options'=>['min_range'=>$array[$i-1]['experience']+1,'max_range'=>$array[$i]['experience']]];
            if(
                filter_var($experience, FILTER_VALIDATE_INT, $options) !== false
            ){
                return $array[$i]['level'];
            }
        }
        return false;

    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户会员信息
     */
    public function level()
    {

        $data = $this->nextLevel($this->userExtra('level'),$this->userExtra('experience'));

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 修改用户配置信息
     */
    public function editExtra()
    {

        $result = self::updateUserExtend($this->user_id);

        if ($result !== false){
            api_return(1,'修改成功');
        }
        api_return(0,'修改失败');
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 根据用户id和要购买的贵族id获取用户购买贵族所需的价格、赠送金额和购买后过期时间
     */
    protected function noblePrice(int $user_id)
    {
        $data = request()->only(['noble_id'],'post');
        $noble = Db::name('noble')->where('noble_id',$data['noble_id'])->cache(60)->find();
        if (!$noble) api_return(0,'参数错误');
        //获取用户当前贵族信息
        $userExtra = $this->userExtra('noble_id,noble_time',$user_id);
        $data['noble_time'] = time() + Time::daysToSecond(31);
        if (
            $data['noble_id'] == $userExtra['noble_id'] &&
            $userExtra['noble_time'] + Time::daysToSecond(31) > time()
        ){
            //处于续费保护期内
            $data['price'] = bcmul($noble['price'],$noble['radio']/100,2);
            $data['give']  = $noble['renew_give'];
            if ($userExtra['noble_time'] > time()){
                $data['noble_time'] = $userExtra['noble_time'] + Time::daysToSecond(31);
            }
        }else{
            $data['price'] = $noble['price'];
            $data['give']  = $noble['give'];
        }

        $data['noble_name'] = $noble['noble_name'];
        return $data;
    }


    /**
     * 金币分享页
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function coinInfo()
    {
        $data = self::getExplain('wx_share,qq_share,wb_share,perfect');
        $data['sum']  = array_sum($data);
        $data['coin'] = $this->userInfo('coin');
        api_return(1,'获取成功',$data);
    }



    /**
     * 第三方账号绑定
     */
    public function thirdBind()
    {

        $data = request()->only(['type','open_id','post']);

        $array = ['wx','qq','wb'];//允许的第三方登录方式

        if (!in_array($data['type'],$array)){
            api_return(0,'无此登录方式');
        }

        $map[$data['type']] = $data['open_id'];
        $userInfo = Db::name('users')->where($map)->find();

        if ($userInfo && $userInfo['user_id'] != $this->user_id){
            api_return(0,'已绑定其他账号!');
        }

        $result = Db::name('users')->where('user_id',$this->user_id)->update([$data['type']=>$data['open_id']]);

        if ($result){
            api_return(1,'绑定成功');
        }
        api_return();

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 礼物赠送成功处理
     */
    protected function gift(array $data,$user_id = null){
        $user_ids = explode(',',$data['to_user']);

        $item['room_id'] = $data['room_id']??0;
        $item['gift_id'] = $data['id'];
        $item['num']     = $data['num']??1;
        if (!$user_id){
            $item['user_id'] = dehashid($data['user_id']);
        }else{
            $item['user_id'] = $user_id;
        }
        $item['total']   = $data['total']??1;
        $item['create_time'] = time();
        $item['update_time'] = time();

        $gift = Db::name('gift')->where('gift_id',$data['id'])->cache(3)->find();
        $detail['type'] = 1;
        $detail['title'] = '来自'.$this->userInfo('nick_name',$item['user_id']).'的'.$gift['gift_name'].'x'.$item['num'];
        $detail['remark'] = '收入';
        $detail['create_time'] = time();
        $detail['update_time'] = time();
        $ratio = $this->extend('gift_ratio') / 100;
        $charge = bcmul($item['total'],$ratio,2);
        $detail['money']    = bcsub($item['total'],$charge,2);
        $detail2['type']    = 2;
        $detail2['remark']  = '消费';
        $detail2['money']   = $item['total'];
        $detail2['user_id'] = $item['user_id'];
        $detail2['create_time'] = time();
        $detail2['update_time'] = time();

        $model = new Logic();
        $model->changeTable('gift_record');

        $array    = [];
        $details  = [];
        $details2 = [];
        foreach ($user_ids as $k => $v){

            $item['to_user'] = dehashid($v);
            if (is_numeric($item['to_user'])){
                $array[] = $item;
                $row = $this->roomInfo($data['room_id'],'room_name,img,type,room_id,is_lock');
                $row['gift_num'] = $item['num'];
                $row['gift_name'] = $gift['gift_name'];
                $row['gift_img'] = $gift['img'];
                $row['thumbnail'] = $gift['thumbnail'];
                $row['send_user_name'] = $this->userInfo('nick_name',$item['user_id']);
                $row['send_user_header'] = $this->userInfo('header_img',$item['user_id']);
                $row['send_user_id'] = $data['user_id'];
                $row['nick_name']   = $this->userInfo('nick_name',$item['to_user']);
                $row['header_img']   = $this->userInfo('header_img',$item['to_user']);
                $row['is_show'] = self::getExplain('is_show') === 'true'?true:false;
                $row['gift_price'] = $gift['price'];

                if ($gift['is_push'] == 1){

//                    $row = $this->roomInfo($data['room_id'],'room_name,img,type,room_id,is_lock');
//                    $row['gift_num'] = $item['num'];
//                    $row['gift_name'] = $gift['gift_name'];
//                    $row['gift_img'] = $gift['img'];
//                    $row['thumbnail'] = $gift['thumbnail'];
//                    $row['send_user_name'] = $this->userInfo('nick_name',$item['user_id']);
//                    $row['send_user_header'] = $this->userInfo('header_img',$item['user_id']);
//                    $row['send_user_id'] = $data['user_id'];
//                    $row['nick_name']   = $this->userInfo('nick_name',$item['to_user']);
//                    $row['header_img']   = $this->userInfo('header_img',$item['to_user']);

                    $this->sendRoomMsg('all','giftPush',$row);
                }

                $detail['user_id'] = $item['to_user'];
                $detail2['title']  = '打赏'.$this->userInfo('nick_name',$item['to_user']).$gift['gift_name'].'x'.$item['num'];
                $details[] = $detail;
                $details2[] = $detail2;

                if ($gift['type'] == 1){
                    //钻石礼物
                    Db::name('users')->where('user_id',$item['to_user'])->setInc('gift_coin',$detail['money']);
                }else{
                    //金币礼物
                    Db::name('users')->where('user_id',$item['to_user'])->setInc('coin',$detail['money']);
                }


                $bigBanner = self::getExplain('bigBanner');
                $smallBanner =  self::getExplain('smallBanner');

                if ($item['total'] >= $smallBanner && $gift['type'] == 1){

                    if ($item['total'] >= $bigBanner){
                        //大横幅推送
                        $this->sendRoomMsg('all','bigBanner',$row);
                    }else{
                        //小横幅推送
                        $this->sendRoomMsg('all','smallBanner',$row);
                    }
                }


            }

        }

        $model->insertAll($array);
        Db::name('money_detail')->insertAll($details);
        Db::name('money_detail')->insertAll($details2);
        if ($data['room_id'] != 0 && $gift['type'] == 1){
            //赠送给麦上用户时判断是否需要进行麦上打赏统计
            if (isset($data['countInfo']) && !empty($data['countInfo'])){
                $class = new Wheat();
                $wheat = $class->getWheat($data['room_id']);
                if ($wheat){
                    $countInfo = explode(',',$data['countInfo']);
                    foreach ($countInfo as $k => $v){
                        if ($wheat[$v-1]['status'] == 1){
                            $wheat[$v-1]['count'] = (string) ($wheat[$v-1]['count']+$item['total']);
                        }
                    }

                    $class->setWheat($data['room_id'],$wheat);
                    $this->refreshWheat($data['room_id'],$wheat);
                }

            }

            if ($gift['type'] == 1){ //钻石礼物
                $hot = bcdiv($data['price'],10) ;
                $hot = intval($hot);
                if ($hot >=1 ){
                    addHot($data['room_id'],$hot,600);
                    //通知到房间热度修改
                    $onlineUser = Db::name('user_extend')->where('room_id',$data['room_id'])->cache(3)->count();

                    //通知到房间热度修改
                    $this->sendRoomMsg($data['room_id'],'hotChange',['hot'=>hotValue($data['room_id']),'onlineUser'=>$onlineUser]);
                }
                    //金币礼物
//                $hot = bcdiv($data['price'],100) * 0.11;
//                $hot = intval($hot);
            }

        }
    }

    public function feedBack()
    {
        $param = request()->only(['content'],'post');
        $param['user_id'] = $this->user_id;
        $logic = new Opinion();
        $res = $logic->saveOpinion($param);
        if($res !== false){
            api_return(1,'反馈成功');
        }
        api_return(0,$logic->getError());
    }


    /**
     * 扣除用户账户钻石、金币、余额
     */
    protected function accountDec($money = 0,$type= 'money',$user_id = null){
        if (!$user_id){
            $user_id = $this->user_id;
        }
        $user = Users::get($user_id);
        switch ($type)
        {
            case 'money':
                if ($money > $user[$type]) api_return(0,'钻石不足，请先充值');
                break;
            case 'coin':
                if ($money > $user[$type]) api_return(0,'金币不足，请先充值');
                break;
            case 'cash':
                api_return(0,'收益不能使用');
                if ($money > $user[$type]) api_return(0,'收益不足，请先充值');
                break;
            default:
                api_return(0,'账户类型错误');
                break;
        }
        $result = $user->setDec($type, $money);
        if (!$result) api_return(0,'扣款失败');
    }


    /**
     * 我的房间我关注的房间列表
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function rooms()
    {
        $map['user_id'] = $this->user_id;
        $map['status']  = ['between','1,3'];
        $rooms = Db::name('room_follow')->where($map)->column('room_id');

        $map['status'] = 1;
        $rooms2 = Db::name('room')->where($map)->column('room_id');

        $rooms = array_unique(array_merge($rooms,$rooms2));

        $where['room_id'] = ['in',$rooms];
        $where['status']  = 1;

        $model = new Room();
        $rows = $model->room($where);

        api_return(1,'获取成功',$rows);
    }

    public function editPwd()
    {
        $data = request()->only(['password'],'post');

//        if (empty($data['phone'])) api_return(0,'请输入手机号码');
        if (empty($data['password'])) api_return(0,'请输入密码');
//        $this->checkCode();
//        $userInfo = Db::name('users')->where('phone',$data['phone'])->find();
//        if (empty($userInfo) || $userInfo['status'] != 1){
//            api_return(0,'用户不存在或被禁用');
//        }

        $model = new \app\common\logic\Users();
        $userInfo['id'] = $this->user_id;
        $userInfo['password'] = $data['password'];
        $result = $model->saveChange($userInfo);

        if ($result !== false){
            cache('token_'.hashid($userInfo['user_id']),null);
            api_return(1,'修改成功');
        }
        api_return(0,$model->getError());
    }

    /**
     * 推广界面
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function spreadView()
    {

        $info = Users::where('user_id',$this->user_id)->field('spread_total,spread_cash')->find();

        $tips = self::getExplain('spread');

        $items = Users::where('proxy_id',$this->user_id)->field('user_id,nick_name,header_img,uuid')->select();

        foreach ($items as $k => $v){

            $map['status']  = 1;
            $map['type']    = 1;
            $map['user_id'] = $v->getData('user_id');

            $items[$k]['total'] = Db::name('bankroll')->where($map)->sum('jewel');
        }

        api_return(1,'获取成功',['info'=>$info,'items'=>$items,'tips'=>$tips]);

    }

    /**
     * 推广余额提现
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function jewel()
    {

        $money = input('money');

        if (!isInt($money)){
            api_return(0,'请输入正确的金额');
        }

        $info = Users::where('user_id',$this->user_id)->field('spread_total,spread_cash')->find();

        if ($info['spread_cash'] < $money){
            api_return(0,'可提现推广奖励不足');
        }

        Db::startTrans();
        try{

            Users::where('user_id',$this->user_id)->setDec('spread_cash',$money);
            $item['user_id'] = $this->user_id;
            $item['money']   = $money;
            $item['create_time'] = time();
            $item['update_time'] = time();
            Db::name('jewel')->insert($item);
            Db::commit();

        }catch (Exception $e){

            Db::rollback();
            api_return(0,$e->getMessage());

        }
        
        api_return(1,'提交成功,请耐心等待管理员审核!');

    }









}
